package com.qiaofei.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qiaofei.mapper.AdminsMapper;
import com.qiaofei.pojo.Admins;
import com.qiaofei.pojo.PageBean;
import com.qiaofei.service.AdminsService;
import com.qiaofei.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AdminsServiceImpl extends BaseServiceImpl implements AdminsService {

    @Autowired
    private AdminsMapper adminsMapper;

    @Override
    public PageBean page(Integer page, Integer pageSize,String name, Short state,LocalDate begin,LocalDate end) {
        //1. 设置分页参数
        PageHelper.startPage(page,pageSize);

        //2. 执行查询
        List<Admins> adminList = adminsMapper.list(name, state, begin, end);
        Page<Admins> p = (Page<Admins>) adminList;

        //3. 封装PageBean对象
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult(), p.getPages());
        return pageBean;
    }

    @Override
    public int add(Admins admins) {
        String salt = RandomStringUtils.randomAlphanumeric(8);
        admins.setSalt(salt);
        admins.setPassword(MD5Utils.getPWD(admins.getPassword()+salt));
        admins.setCreateTime(LocalDateTime.now());

        return adminsMapper.insert(admins);
    }

    @Override
    public void update(Map<String, Object> data) {

        Admins admins = null;
        String oldHeader = "";
        int result = 0;
        int id = (int) data.get("id");
        List<Integer> ids = new ArrayList<>();
        ids.add(id);
        List<Admins> oldAdminList = getByIds(ids);
        Admins oldAdmin = oldAdminList != null? oldAdminList.get(0) :null;
        oldHeader = oldAdmin.getHeader();
        if(data.get("admin") != null) {
            //转换成实体类
            Object adminsObj = data.get("admin");
            String adminsStr = JSON.toJSONString(adminsObj);
            admins = JSONObject.parseObject(adminsStr, Admins.class);
            System.out.println(admins);
            if (admins.getPassword() != null && admins.getPassword().equals("") == false) {
                admins.setPassword(MD5Utils.getPWD(admins.getPassword() + admins.getSalt()));
            }
            admins.setUpdateTime(LocalDateTime.now());
            result = adminsMapper.update(admins);
        }
        try {
            String path = ResourceUtils.getURL("classpath:").getPath();
            File upload = new File(path);
            String uploadPath = upload.getAbsolutePath()+ "/";

            List<String> fileList = (List<String>) data.get("fileList");
            for (String item :
                    fileList) {
                if(item.equals("") == false) {
                    if ((result > 0 && item.equals(admins.getHeader()) == false)
                            || (result == 0 && item.equals(oldHeader) == false)) {
                        Path path2 = Paths.get(uploadPath + item);
                        System.out.println(path2);
                        if (Files.exists(path2)) {
                            Files.delete(path2);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Admins> getByIds(List<Integer> ids) {
        List<Admins> adminsList = adminsMapper.getByIds(ids);
        return adminsList;
    }

    @Override
    public void deleted(List<Integer> ids) {
        List<Admins> adminsList = getByIds(ids);
        List<String> headerList = new ArrayList<>();
        if(adminsList.size() > 0){
            for (Admins admin :
                    adminsList) {
                if(admin.getHeader().equals("") == false) {
                    headerList.add(admin.getHeader());
                }
            }
            deleteImages(headerList);
        }
        adminsMapper.delete(ids);
    }

    public Admins login(Admins admin) {
        return adminsMapper.getByUsernameAndPassword(admin);
    }
}
